package cn.xd.base.application.service.command.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.xd.base.application.service.command.GlobalAppUserAppService;
import cn.xd.base.basic.type.GlobalAppUserId;
import cn.xd.base.basic.type.Password;
import cn.xd.base.domain.bean.command.ChangePasswordCommand;
import cn.xd.base.domain.bean.command.CreateUserCommand;
import cn.xd.base.domain.entity.AppUserThirdParty;
import cn.xd.base.domain.entity.GlobalAppUser;
import cn.xd.base.domain.repository.GlobalAppUserRepository;
import cn.xd.base.persistence.dos.AppUserThirdPartyDO;
import cn.xd.base.persistence.mps.AppUserThirdPartyMpService;
import cn.xd.base.persistence.mps.GlobalAppUserMpService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GlobalAppUserAppServiceImpl implements GlobalAppUserAppService {

    @Resource
    private GlobalAppUserRepository globalAppUserRepository;
    @Resource
    private GlobalAppUserMpService globalAppUserMpService;
    @Resource
    private AppUserThirdPartyMpService appUserThirdPartyMpService;

    @Override
    public Long register(CreateUserCommand command) {
        GlobalAppUser globalAppUser = GlobalAppUser.register(command);
        globalAppUserRepository.save(globalAppUser);
        return globalAppUser.getId().getValue();
    }

    @Override
    public GlobalAppUser getGlobalAppUserByPhone(String phone) {
        return globalAppUserRepository.getGlobalAppUserByPhone(phone);
    }

    @Override
    public String getGlobalAppUserPhone(String openId, String unionId, Integer type, Integer appUserType) {
        AppUserThirdPartyDO appUserThirdPartyDO = appUserThirdPartyMpService.getAppUserThirdPartyDO(openId, unionId, type, appUserType).get();
        if (ObjUtil.isEmpty(appUserThirdPartyDO)) {
            return null;
        }
        return globalAppUserMpService.getById(appUserThirdPartyDO.getUserId()).getPhone();
    }

    @Override
    public void addAppUserThirdParty(GlobalAppUser user, String openId, String unionId, Integer type, Integer appUserType) {
        List<AppUserThirdParty> appUserThirdParties = user.getThirdPartyList().stream().filter(item -> item.getType().getValue().equals(type) && item.getAppUserType().getValue().equals(appUserType)).toList();
        if (CollUtil.isEmpty(appUserThirdParties)) {
            user.addThirdPartyList(openId, unionId, type, appUserType);
            globalAppUserRepository.save(user);
        }
    }

    @Override
    public void changePassword(ChangePasswordCommand command) {
        GlobalAppUser globalAppUser = globalAppUserRepository.find(GlobalAppUserId.of(command.getId())).isEmptyThrow("找不到用户");
        globalAppUser.changePassword(Password.encrypt(command.getPassword()));
        globalAppUserRepository.save(globalAppUser);
    }


}
